package com.sumainfor.zuul.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.SysUserVo;
import com.sumainfor.common.exception.LoginFailureException;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.zuul.entity.SysUserEntity;
import com.sumainfor.zuul.util.HttpContextUtils;
import com.sumainfor.zuul.util.JwtHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.codec.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@Component
public class WxSystemZullFilter extends ZuulFilter {

    private Logger log =  LoggerFactory.getLogger(getClass());

    @Autowired
    private JwtHelper jwtHelper;

    private String prefix = "/wxsys/";

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        String path = request.getServletPath();
        if (path.startsWith(prefix)) {
            return true;
        }
        return false;
    }

    @Override
    public Object run() {
        //判断权限
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();

        RequestContext ctx = RequestContext.getCurrentContext();

        String token = ctx.getRequest().getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            try {
                ctx.setSendZuulResponse(false);
                ctx.getResponse().setHeader("Content-Type","application/json");
                PrintWriter writer = ctx.getResponse().getWriter();
                writer.write(JsonResult.error("缺失Token", 401).toJson());
                writer.flush();
                writer.close();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        SysUserEntity user = null;
        try {
            user = jwtHelper.validateTokenAndGetClaims(token);
        } catch (LoginFailureException e) {
            ctx.setSendZuulResponse(false);
            ctx.getResponse().setHeader("Content-Type","application/json");
            PrintWriter writer = null;
            try {
                writer = ctx.getResponse().getWriter();
            } catch (IOException t) {
                t.printStackTrace();
            }
            writer.write(JsonResult.error(e.getMessage(), 401).toJson());
            writer.flush();
            writer.close();
            return null;
        }

        //构建Vo 对象
        SysUserVo userVo = new SysUserVo();
        userVo.setAreaId(user.getAreaId());
        userVo.setDeptId(user.getDeptId());
        userVo.setUserId(user.getUserId());
        userVo.setDeptName(user.getDeptName());
        userVo.setLoginName(user.getLoginName());
        userVo.setNo(user.getNo());
        userVo.setName(user.getName());
        userVo.setEmail(user.getEmail());
        userVo.setPhone(user.getPhone());
        userVo.setMobile(user.getMobile());
        userVo.setRoleIdList(user.getRoleIdList());
        userVo.setParentDeptVo(user.getParentDeptVo());
        userVo.setDefaultServiceDeptChild(user.getCenterServiceChild());
        userVo.setBottomDeptList(user.getBottomDeptList());

        try {
            ctx.addZuulRequestHeader(Constants.HEAD_USER_ID, Base64.encodeToString(JSONObject.toJSONString(userVo).getBytes("UTF-8")));
            ctx.addZuulRequestHeader(Constants.HEAD_TYPE, String.valueOf(Constants.HeadType.SYS.getCode()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

       /* logger.info("转发服务URL ===> {}\n转发附带Header ====> {} \n 参数 ====> {}",
                request.getServletPath(),
                ctx.getZuulRequestHeaders().toString(),
                request.getParameterMap().toString());*/

        log.debug("转发服务 WX_System URL ===> {}", request.getServletPath());
        return null;
    }
}
